package com.fiveup.core.performanceevaluation.controller;

import com.alibaba.fastjson.JSON;
import com.fiveup.core.performanceevaluation.bean.StudentPerformance;
import com.fiveup.core.performanceevaluation.dto.PageDto;
import com.fiveup.core.performanceevaluation.service.StudentPerformanceService;
import com.fiveup.core.performanceevaluation.service.SubjectScoreWeightService;
import com.fiveup.core.performanceevaluation.utils.Result;
import com.fiveup.core.performanceevaluation.utils.StudentPerformanceUtil;
import com.fiveup.core.performanceevaluation.vo.AdvantageSubjects;
import com.fiveup.core.performanceevaluation.vo.Average;
import com.fiveup.core.performanceevaluation.vo.StudentPerformanceVO;
import com.fiveup.core.performanceevaluation.vo.SubjectScoreWeightVO;
import jnr.ffi.annotations.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理与学生表现相关的请求
 */
@Controller
@CrossOrigin
@RequestMapping("/performance")
public class StudentPerformanceController {

    @Autowired
    private StudentPerformanceService studentPerformanceService;

    @Autowired
    private SubjectScoreWeightService subjectScoreWeightService;

    /**
     * 获取所有记录
     * @return
     */
    @ResponseBody
    @RequestMapping("/all")
    public String getAllList(Integer tid) {
        Result result = new Result();
        List<StudentPerformanceVO> all = new ArrayList<>();
        String sql = new String();

        if(tid == 100000){
            sql = "select count(id) from student_performance";
            all = studentPerformanceService.getAll();
        }else{
            sql = "select count(id) from student_performance where tid = " + tid;
            all = studentPerformanceService.getByTId(tid);
        }
        // 获取记录数
        Integer count = studentPerformanceService.getCount(sql);

//        List<StudentPerformanceVO> all = studentPerformanceService.getAll();
        result.setCode(600);
        result.setMsg("查询成功！");
        result.setData(all);
        result.setCount(count);
        return JSON.toJSON(result).toString();
    }

    /**
     * 根据分页获取
     * @return
     */
    @ResponseBody
    @PostMapping("/list")
    public String getAllList(@RequestBody PageDto pageDto) {
        Result result = new Result();
        // 获取记录数
        String sql = "select count(id) from student_performance";
        Integer count = studentPerformanceService.getCount(sql);

        // 根据分页数据查询值
        List<StudentPerformanceVO> list = studentPerformanceService.getPagination(
                (pageDto.getCurrentPage() - 1) * pageDto.getPageSize(),
                        pageDto.getPageSize());
        result.setCode(600);
        result.setMsg("查询成功！");
        result.setData(list);
        result.setCount(count);
        return JSON.toJSON(result).toString();
    }

    /**
     * 验证学号是否存在
     * @return
     */
    @ResponseBody
    @GetMapping("/exist")
    public String exist(Integer sid) {
        Result result = new Result();
        // 查询是否存在
        StudentPerformanceVO bySid = studentPerformanceService.getBySid(sid);
        result.setCode(600);
        result.setMsg("查询成功！");
        result.setData(bySid);
        return JSON.toJSON(result).toString();
    }


    /**
     * 增加数据
     * @param studentPerformance
     * @return
     */
    @ResponseBody
    @PostMapping("/add")
    public String add(@RequestBody StudentPerformance studentPerformance){
        Result result = new Result();

        // 增加
        studentPerformanceService.add(studentPerformance);

        // 查询封装后的数据
        StudentPerformanceVO bySid = studentPerformanceService.getById(studentPerformance.getId());
        result.setCode(600);
        result.setData(bySid);
        result.setMsg("增加成功");
        return JSON.toJSON(result).toString();
    }

    /**
     * 更新数据
     * @param studentPerformance
     * @return
     */
    @ResponseBody
    @PutMapping("/update")
    public String update(@RequestBody StudentPerformance studentPerformance){
        Result result = new Result();

        if(studentPerformance.getTotalScore() != null) {
            // 已经生成过总评成绩了，需要重新计算
            // 查询该学生成绩对应的老师权重
            SubjectScoreWeightVO byTId = subjectScoreWeightService.getByTId(studentPerformance.getTid());

            // 生成总评成绩
            BigDecimal bigDecimal = StudentPerformanceUtil.computeTotalScore(studentPerformance, byTId);

            // 设置总评成绩
            studentPerformance.setTotalScore(bigDecimal);
        }

        // 更新
        studentPerformanceService.updateById(studentPerformance);

        // 查询更新后的数据
        StudentPerformanceVO byId = studentPerformanceService.getById(studentPerformance.getId());
        result.setCode(600);
        result.setData(byId);
        result.setMsg("更新成功！");
        return JSON.toJSON(result).toString();
    }


    /**
     * 删除数据
     * @param studentPerformance
     * @return
     */
    @ResponseBody
    @DeleteMapping("/delete")
    public String delete(@RequestBody StudentPerformance studentPerformance) {
        Result result =  new Result();

        // 删除
        studentPerformanceService.deleteById(studentPerformance.getId());

        result.setCode(600);
        result.setMsg("删除成功！");
        return JSON.toJSON(result).toString();
    }


    /**
     * 生成总评成绩
     * @param studentPerformance
     * @return
     */
    @ResponseBody
    @PutMapping("/generate")
    public String generateTotalScore(@RequestBody StudentPerformance studentPerformance){
        Result result = new Result();

        // 查询该学生成绩对应的老师权重
        SubjectScoreWeightVO byTId = subjectScoreWeightService.getByTId(studentPerformance.getTid());

        // 生成总评成绩
        BigDecimal bigDecimal = StudentPerformanceUtil.computeTotalScore(studentPerformance, byTId);

        // 设置总评成绩
        studentPerformance.setTotalScore(bigDecimal);
        // 更新
        studentPerformanceService.updateById(studentPerformance);

        // 查询更新后的数据
        StudentPerformanceVO byId = studentPerformanceService.getById(studentPerformance.getId());
        result.setCode(600);
        result.setData(byId);
        result.setMsg("更新成功！");
        return JSON.toJSON(result).toString();
    }


    /**
     * 根据教师ID查询对应的5个方面平均分对象
     * @param tid
     * @return
     */
    @ResponseBody
    @GetMapping("/avg")
    public String getAverage(Integer tid) {
        Result result = new Result();

        // 查询
        Average averageByTid = studentPerformanceService.getAverageByTid(tid);
        averageByTid.setTid(tid);

        result.setCode(600);
        result.setData(averageByTid);
        result.setMsg("查询成功！");

        return JSON.toJSON(result).toString();
    }

    /**
     * 验证学号对应的数据信息
     * @return
     */
    @ResponseBody
    @GetMapping("/get")
    public String get(Integer sid) {
        Result result = new Result();
        // 查询数据
        StudentPerformanceVO bySid = studentPerformanceService.getBySid(sid);
        if(bySid != null) {
            result.setCode(600);
            result.setMsg("查询成功！");
            result.setData(bySid);
        } else {
            result.setCode(602);
            result.setMsg("该学号对应的数据信息不存在！");
        }
        return JSON.toJSON(result).toString();
    }


    /**
     * 根据老师ID查询所在班级的所有同学信息
     * @param tid
     * @return
     */
    @ResponseBody
    @GetMapping("/class")
    public String getList(Integer tid) {
        Result result = new Result();

        // 查询数据
        List<StudentPerformanceVO> byTId = studentPerformanceService.getByTId(tid);
        result.setCode(600);
        result.setCount(byTId.size());
        result.setData(byTId);
        result.setMsg("查询成功！");
        return JSON.toJSON(result).toString();
    }

    /**
     * 查询教师ID对应的除查询的学生之外的所有学生的总数
     * @param tid
     * @param sid
     * @return
     */
    @ResponseBody
    @GetMapping("/sum")
    public String sum(Integer tid, Integer sid) {
        Result result = new Result();

        // 查询5个方面和数据
        List<Integer> subjectScoreSum = studentPerformanceService.getSubjectScoreSum(tid, sid);
        result.setCode(600);
        result.setData(subjectScoreSum);
        result.setMsg("查询成功！");
        return JSON.toJSON(result).toString();
    }

    /**
     * 查询教师ID对应的班级优势科目人数
     * @param tid
     * @return
     */
    @ResponseBody
    @GetMapping("/as")
    public String getAdvantageSubject(Integer tid,Integer score) {
        Result result = new Result();

        // 所需字段
        String statisticalFields[] = new String[]
                {"virtue", "intelligence", "sports", "art", "labor"};
        Integer nums[] = new Integer[6];

        // 创建一个优势科目对象
        for (int i = 0; i < statisticalFields.length; i++) {
            String sql = "select count(" + statisticalFields[i] + ") from student_performance "
                    + "where " + statisticalFields[i] + " >= "+ score +" and tid = " + tid;
            nums[i] = studentPerformanceService.getCount(sql);
        }

        String sql = "select count(id) from student_performance where tid = " + tid;
        nums[5] = studentPerformanceService.getCount(sql);

        AdvantageSubjects advantageSubjects = new AdvantageSubjects();
        // 设置值
        advantageSubjects.setVirtue(nums[0]);
        advantageSubjects.setIntelligence(nums[1]);
        advantageSubjects.setSports(nums[2]);
        advantageSubjects.setArt(nums[3]);
        advantageSubjects.setLabor(nums[4]);
        advantageSubjects.setTotalNum(nums[5]);

        result.setCode(600);
        result.setData(advantageSubjects);
        result.setMsg("查询成功！");
        return JSON.toJSON(result).toString();
    }
}
